package com.nxy.cpfsfe.busi.bbatproc;

import com.adtec.starring.datapool.CompSDO;
import com.adtec.starring.datapool.EPOper;
import com.adtec.starring.exception.BaseException;
import com.adtec.starring.global.SysDef;
import com.adtec.starring.respool.SystemParameter;
import com.adtec.starring.struct.dta.DtaInfo;
import com.adtec.starring.util.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.nxy.cpfsfe.PubBeanSerial;
import com.nxy.cpfsfe.config.CpfsFeAllConfig;
import com.nxy.cpfsfe.enumtype.MsgCdOrTpEnum;
import com.nxy.cpfsfe.enumtype.RespCd;
import com.nxy.cpfsfe.enumtype.RpcOutputInfoEnum;
import com.nxy.cpfsfe.enumtype.SysEcodeEnum;
import com.nxy.cpfsfe.mybatis.mapper.ToNcsCrdlMapper;
import com.nxy.cpfsfe.mybatis.pojo.ToNcsCrdl;
import com.nxy.cpfsfe.util.DateUtil;
import com.nxy.cpfsfe.util.RpcCommUtil;
import com.nxy.cpfsfe.util.XMLNodeUtil;
import org.apache.ibatis.session.SqlSession;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class BBatDgtlCrdlSrvBean {
	/**
	 * Description: 处理内管数字证书绑定通知报文
	 * @author  wp
	 * @date 2019年9月16日
	 * 
	 */
		
	private final static Logger LOGGER = LoggerFactory.getLogger(BBatDgtlCrdlSrvBean.class);
	SqlSession sqlSession = (SqlSession) SpringUtil.getBean("mybatisSqlSession");	
	
	
	public void bBatDgtlCrdlSrv() {
		String bizMsg=null;
		String tpId = DtaInfo.getInstance().getTpId();	
		// 获取输入
		CompSDO inputSdo = (CompSDO) EPOper.getCompSDO(tpId, "ReqBody"); // 获取输入接口		
		bizMsg = (String) inputSdo.getValue("BizMsg")!=null?(String) inputSdo.getValue("BizMsg"):"";
		//String sndAppCd = (String) EPOper.get(tpId, "ReqBean[0].head[0].sndAppCd");
		LOGGER.debug("接收到输入BizMsg报文数据:[{}]" , bizMsg);
		JSONObject jsonObject = JSONObject.parseObject(bizMsg);
		//TODO 处理数字证书绑定
		String bankNo = jsonObject.getString("bankNo");
		String bndFlg = jsonObject.getString("bndFlg");
		LOGGER.debug("发送成员行行号:[{}]" , bankNo);
		LOGGER.debug("绑定标识:[{}]" , bndFlg);
		//获取DN值
		ToNcsCrdl toNcsCrdl = new ToNcsCrdl();
		toNcsCrdl.setBankNo(bankNo);
		ToNcsCrdlMapper toNcsCrdlMap = sqlSession.getMapper(ToNcsCrdlMapper.class);
		ToNcsCrdl toNcsCrdlOb = toNcsCrdlMap.queryByBNo(toNcsCrdl);
		if(null != toNcsCrdlOb){
			String crdlDN = toNcsCrdlOb.getCrdlDN();
			returnGWNPS903(bankNo,bndFlg,crdlDN);
			
		}else{
			LOGGER.error("数据证书为空");
		}
		 		
		CompSDO outputSdo = EPOper.getCompSDO(tpId, "RspBody"); // 获取输出接口
		EPOper.put(tpId, "RspBean[0].head[0].rspsCd", "0000000");
		EPOper.put(tpId, "RspBean[0].head[0].respsInfoDesc", "处理中");
		List<Object> list = new ArrayList<Object>();
        Map<String, Object> map1 = new HashMap<String, Object>();
		String msg = "正在处理中，请稍后";
        map1.put("BizMsg",msg);
        JSONObject json = new JSONObject();
        json = new JSONObject(map1);
        list.add(json);       
        outputSdo.setValue("BizMsg", JSONObject.toJSONString(list));
	}
	
	public void returnGWNPS903(String sndMbrCd,String bndFlg,String crdlDN ){
		String tpId = DtaInfo.getInstance().getTpId();		
		String bizMsg903 = buildDgtCrdlXml(sndMbrCd,bndFlg);
		LOGGER.debug("NPS903报文[{}]",bizMsg903);		
		//转发给网关
	    LOGGER.debug("rpc调用网关发送NPS903开始......");
	    try{
	    	EPOper.put(tpId, "ReqBean[0].head[0].sndAppCd", SysEcodeEnum.CPFS.getCode());
		    EPOper.put(tpId, "ReqBean[0].head[0].rcvAppCd", SysEcodeEnum.NCS.getCode());
	    	EPOper.put(tpId, "ReqBean[0].head[0].reqServCd", MsgCdOrTpEnum.MSGCD_903.getCode());
	    	EPOper.put(tpId, "ReqBean[0].head[0].crdlDN", crdlDN);
	    	String seqNo = PubBeanSerial.getInstance().getSeqNoAndIncrea(SysEcodeEnum.CPFS.getCode());
	    	EPOper.put(tpId, "ReqBean[0].head[0].initrSeqno",seqNo);
		    EPOper.getCompSDO(tpId, "ReqBody").setValue("BizMsg", bizMsg903);
			RpcCommUtil.getInstance().rpcFeToGW(tpId, RpcOutputInfoEnum.OutputName_Pub_Cpfsgw.getCode(),RpcOutputInfoEnum.OutPutSvr_CpfsFwdThrdPrtS.getCode());	
	    }catch(Exception e){
	    	LOGGER.error("调用网关转发NPS.903报文服务失败",e);
			throw new BaseException(RespCd.NCPO6047,e,"调用网关服务异常");
	    }
	    
	}
	

	
	// 组装NPS.903报文   
	public static String buildDgtCrdlXml(String sndMbrCd,String chgTp) {
		LOGGER.info("---------数字证书绑定通知报文--------");
		try {

	        	XMLNodeUtil xmlReqDoc;
			    xmlReqDoc = new XMLNodeUtil(XMLNodeUtil.FROM_FILE,  SysDef.WORK_DIR + SystemParameter.SRC_PATH + SysDef.FILE_SP+"xml" + SysDef.FILE_SP+"NPS_903.xml");
			    Date date = new Date();
	        	String seqNb = PubBeanSerial.getInstance().getSeqNoAndIncrea("seqNb"); 
	        	String msgId = PubBeanSerial.getInstance().getSeqNoAndIncrea("MSGID");
	        	LOGGER.debug("seqNb=[{}]",seqNb);
	        	LOGGER.debug("msgId=[{}]",msgId);
	        	xmlReqDoc.setNodeContentTrim("/transaction/header/msg/sndAppCd","MPS");
	        	xmlReqDoc.setNodeContentTrim("/transaction/header/msg/sndMbrCd",sndMbrCd);
	        	xmlReqDoc.setNodeContentTrim("/transaction/header/msg/sndDt",DateUtil.getDate());
	        	xmlReqDoc.setNodeContentTrim("/transaction/header/msg/sndTm",DateUtil.getTime());
	        	xmlReqDoc.setNodeContentTrim("/transaction/header/msg/rcvAppCd","NPS");
	        	xmlReqDoc.setNodeContentTrim("/transaction/header/msg/rcvMbrCd","100000000000");
	        	xmlReqDoc.setNodeContentTrim("/transaction/header/msg/seqNb",seqNb);
	        	xmlReqDoc.setNodeContentTrim("/transaction/header/msg/structType","XML");
	        	xmlReqDoc.setNodeContentTrim("/transaction/header/msg/callTyp","ASYN");
	        	xmlReqDoc.setNodeContentTrim("/transaction/body/CertNtfctn/GrpHdr/MsgId",msgId);
	        	xmlReqDoc.setNodeContentTrim("/transaction/body/CertNtfctn/GrpHdr/CreDtTm",DateUtil.getISODateTime(date));
	        	xmlReqDoc.setNodeContentTrim("/transaction/body/CertNtfctn/GrpHdr/InstgPty/InstgDrctPty",sndMbrCd);
	        	xmlReqDoc.setNodeContentTrim("/transaction/body/CertNtfctn/GrpHdr/InstgPty/InstgPty",sndMbrCd);
	        	xmlReqDoc.setNodeContentTrim("/transaction/body/CertNtfctn/GrpHdr/InstdPty/InstdDrctPty","100000000000"); 
	        	xmlReqDoc.setNodeContentTrim("/transaction/body/CertNtfctn/GrpHdr/InstdPty/InstdPty","100000000000");
	        	/*xmlReqDoc.setNodeContentTrim("/transaction/body/CertNtfctn/GrpHdr/BizTyp","");
	        	xmlReqDoc.setNodeContentTrim("/transaction/body/CertNtfctn/GrpHdr/BizKind","");*/
	        	xmlReqDoc.setNodeContentTrim("/transaction/body/CertNtfctn/GrpHdr/TranChnlTyp","06");
	        	//xmlReqDoc.setNodeContentTrim("/transaction/body/CertNtfctn/GrpHdr/Rmk","");
	        	xmlReqDoc.setNodeContentTrim("/transaction/body/CertNtfctn/CertNtfctnInf/ChgTp",chgTp);
	        	xmlReqDoc.setNodeContentTrim("/transaction/signature","");	        	
	        	String msg = xmlReqDoc.toString();	 	   		
		   		msg = msg.replace("<transaction>", "<transaction xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"urn:ncs2:std:nps:2012:tech:xsd:NPS.903.001.01\">");
		   	    //将msg和chgTp放入redis
				CpfsFeAllConfig.jedisCluster.setex(msgId, 60, chgTp);
		   		return msg;

		} catch (DocumentException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			throw new BaseException("数字证书绑定通知组装失败",e);
		}
	}
}
